package com.atguigu.tingshu.search.receiver;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import co.elastic.clients.elasticsearch.core.UpdateByQueryResponse;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SearchReceiver {
    @Autowired
    private SearchService searchService;
    @Autowired
    private ElasticsearchClient elasticsearchClient;
    @Autowired
    private RedisTemplate redisTemplate;

    //创建消息队列的消费者，创建交换机、路由键、队列

    /**
     * 保存专辑文档到索引库中
     *
     * @param albumId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void receiveUpper(Long albumId, Message message, Channel channel) {
        if (albumId != null) {
            log.info("[搜索服务]监听到专辑上架消息：{}", albumId);
            searchService.upperAlbum(albumId);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 删除索引库中的专辑文档
     *
     * @param albumId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.ROUTING_ALBUM_LOWER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void receiveLower(Long albumId, Message message, Channel channel) {
        if (albumId != null) {
            log.info("[搜索服务]监听到专辑下架/删除消息：{}", albumId);
            searchService.lowerAlbum(albumId);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    private static final String INDEX_NAME = "albuminfo";


    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ALBUM_ES_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateAlbumEs(TrackStatMqVo trackStatMqVo, Message message, Channel channel) {
        if (trackStatMqVo != null) {
            log.info("[搜索服务]监听到声音播放统计消息：{}", trackStatMqVo);
            String key = RedisConstant.BUSINESS_PREFIX + "es:" + trackStatMqVo.getBusinessNo();
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
            if (flag) {
                try {
                    Long albumId = trackStatMqVo.getAlbumId();
                    String statType = trackStatMqVo.getStatType();
                    searchService.addAlbumNum(albumId,statType);

                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (Exception e) {
                    log.error("[搜索服务]更新索引库失败：{}", e);
                    redisTemplate.delete(key);
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                }

            }

        }
    }
}
